/**
 * Created by MyPC on 2017/6/21.
 */
let fs = require('fs');
let path = require('path');
let snowflake = require('node-snowflake').Snowflake;
let moment = require('moment');

// 判断路径是否存在,不存在则创建
function mkdir(dirpath) {
  if (!fs.existsSync(dirpath)) {
    let pathtmp;
    let array = dirpath.split(path.sep);
    array.forEach(function(dirname) {
      if (pathtmp) {
        pathtmp = path.join(pathtmp, dirname);
      } else {
        pathtmp = dirname;
      }
      if (dirname!=='' && dirname.indexOf('.')===-1 && !fs.existsSync(pathtmp)) {
        if (!fs.mkdirSync(pathtmp)) {
          return false;
        }
      }
    });
  }
  return true;
}

function formatFilePath(str, filename) {
  let time = moment();
  let name = str.replace(/{time}/g, time.valueOf())
      .replace(/{yyyy}/g, moment().format('YYYY'))
      .replace(/{yy}/g, moment().format('YY'))
      .replace(/{mm}/g, moment().format('MM'))
      .replace(/{dd}/g, moment().format('DD'))
      .replace(/{hh}/g, moment().format('HH'))
      .replace(/{ii}/g, moment().format('mm'))
      .replace(/{ss}/g, moment().format('ss'))
      .replace(/{rand:\d*?}/g, snowflake.nextId());
  if(filename){
    name = name.replace(/{filename}/g, filename)
        .replace(/{suffix}/g, path.extname(filename));
  }
  return name;
}

module.exports = {
  'formatFilePath': formatFilePath,
  'mkdir': mkdir,
};
